﻿using System;
using System.Collections.Generic;
using AuctionClassLibrary;

namespace Server
{
    public class GetDataFromDatabase
    {
        private DBHelper _db;
        private Auction _auction;
        private List<Auction> _auctions;

        public GetDataFromDatabase()
        {
            _auctions = new List<Auction>();
        }

        public List<Auction> GetProducts()
        {
            try
            {
                // Connect to DB
                _db = new DBHelper("ealdb1.eal.local", "ejl05_usr", "Baz1nga5");
                _db.Connect();

                // Get products
                _db.Open();
                _db.SelectData("Id, UserId, DateCreated, EndDate, Name, Description, StartPrice, EstimatedPrice, Sold", "AH_Auction", "Sold = '0'", "Name");
                while (_db.data.Read())
                {
                    string name = _db.data["Name"].ToString();
                    decimal startPrice = (decimal)_db.data["StartPrice"];
                    decimal estimatedPrice = (decimal)_db.data["EstimatedPrice"];
                    DateTime created = (_db.data["DateCreated"] == DBNull.Value) ? DateTime.Today : Convert.ToDateTime(_db.data["DateCreated"]);
                    DateTime end = (_db.data["EndDate"] == DBNull.Value) ? DateTime.Today : Convert.ToDateTime(_db.data["EndDate"]);
                    bool sold = (bool)_db.data["Sold"];
                    string description = _db.data["Description"].ToString();

                    _auction = new Auction(name, startPrice, estimatedPrice, created, end, sold, description);
                    _auctions.Add(_auction);
                }
                _db.Close();
                return _auctions;
            }
            catch (Exception) { return null; }
        }
    }
}
